#include "device.h"
#include "color.h"
#include "usart.h"

Col_inf col_inf;

//设置颜色传感器上led亮度
void Set_brightness(u8 percent)
{
  u8 data[2];
  data[0] = 0xc1;
  data[1] = percent;
  HAL_UART_Transmit(&uart3_handle, data, 2, 10);
}

//白平衡
void Set_white_balance()
{
  u8 data = 0xc2;
  HAL_UART_Transmit(&uart3_handle, &data, 1, 10);
  delay_ms(1000);
}

//获取一次被测物体的RGB值
void Get_RGB_val()
{
  u8 data = 0xd8;
  HAL_UART_Transmit(&uart3_handle, &data, 1, 10);
}

//多次测量取平均值
void Get_average_RGB(u8 time)
{
  u8 data = 0xd8;

  static int r_value, g_value, b_value;
  for (u8 i = 0; i < time; i++)
  {
    HAL_UART_Transmit(&uart3_handle, &data, 1, 10);
    delay_ms(50);
//    r_value += RGB_VAL[2];
//    g_value += RGB_VAL[3];
//    b_value += RGB_VAL[4];
  }
  col_inf.r_val = r_value / time;
  col_inf.g_val = g_value / time;
  col_inf.b_val = b_value / time;

  r_value = 0;
  g_value = 0;
  b_value = 0;
}

//根据得到的RGB值，判断被测物块的颜色并返回
Color_type judge_color()
{
  if (col_inf.r_val > 200 && col_inf.g_val > 200 && col_inf.b_val > 200)
    col_inf.color = WHITE;
  else if (col_inf.r_val < 120 && col_inf.g_val < 120 && col_inf.b_val < 120)
    col_inf.color = BLACK;
  else if (col_inf.r_val < 180 && col_inf.b_val > 230)
    col_inf.color = BLUE;
  else if (col_inf.r_val > 200 && col_inf.g_val < 180 && col_inf.b_val < 180)
    col_inf.color = RED;
  else
    col_inf.color = Uknown;

  return col_inf.color;
}
